package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.*;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service(version = "1.0.0")
public class QuanZiApiImpl implements QuanZiApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Override
    public String savePublish(Publish publish) {
        //校验user
        if (publish.getUserId() == null) {
            return null;
        }
        publish.setId(ObjectId.get());
        publish.setCreated(System.currentTimeMillis());
        publish.setSeeType(1);

        publish.setPid(idService.createId("publish", publish.getId().toHexString()));

        this.mongoTemplate.save(publish);

        //album往自己相册里面写数据
        Album album = new Album();
        album.setId(ObjectId.get());
        album.setPublishId(publish.getId());
        album.setCreated(System.currentTimeMillis());

        this.mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());

        //向好友时间线表写数据
        Query query = Query.query(Criteria.where("userId").is(publish.getUserId()));
        List<Users> users = this.mongoTemplate.find(query, Users.class);

        for (Users user : users) {
            TimeLine timeLine = new TimeLine();
            timeLine.setId(ObjectId.get());
            timeLine.setPublishId(publish.getId());
            timeLine.setDate(System.currentTimeMillis());
            timeLine.setUserId(publish.getUserId());

            this.mongoTemplate.save(timeLine, "quanzi_time_line_" + user.getFriendId());

        }

        return publish.getId().toHexString();
    }

    @Override
    public List<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {
        //首先要查时间线表
        PageRequest pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date")));
        Query query = new Query().with(pageable);


        String tableName = "quanzi_time_line_recommend";
        if (userId != null) {
            tableName = "quanzi_time_line_" + userId;
        }

        List<TimeLine> timeLines = this.mongoTemplate.find(query, TimeLine.class, tableName);

        //获取publishId集合
        Set<ObjectId> idSet = timeLines.stream().map(TimeLine::getPublishId).collect(Collectors.toSet());


        //查询发布详情
        Query query1 = Query.query(Criteria.where("id").in(idSet)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishes = this.mongoTemplate.find(query1, Publish.class);

        return publishes;
    }

    @Override
    public boolean saveLikeComment(Long userId, String publishId) {
        //先判断有没有爱过
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId).and("commentType").is(1));
        long count = this.mongoTemplate.count(query, Comment.class);

        if (count > 0) {
            return false;
        }

        return this.saveComment(userId, publishId, 1, null);
    }

    @Override
    public boolean removeComment(Long userId, String publishId, Integer commentType) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId).and("commentType").is(commentType));

        return this.mongoTemplate.remove(query, Comment.class).getDeletedCount() == 1;
    }

    @Override
    public boolean saveLoveComment(Long userId, String publishId) {
        //先判断有没有爱过
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId).and("commentType").is(3));
        long count = this.mongoTemplate.count(query, Comment.class);

        if (count > 0) {
            return false;
        }

        return this.saveComment(userId, publishId, 3, null);
    }

    @Override
    public boolean saveComment(Long userId, String publishId, Integer type, String content) {
        Comment comment = new Comment();
        comment.setId(ObjectId.get());
        comment.setCommentType(type);
        comment.setUserId(userId);
        comment.setCreated(System.currentTimeMillis());
        comment.setIsParent(true);
        comment.setParentId(null);
        comment.setPublishId(new ObjectId(publishId));
        comment.setContent(content);

        // 设置发布人的id
        Publish publish = this.mongoTemplate.findById(comment.getPublishId(), Publish.class);
        if (null != publish) {
            comment.setPublishUserId(publish.getUserId());
        } else {
            Video video = this.mongoTemplate.findById(comment.getPublishId(), Video.class);
            if (null != video) {
                comment.setPublishUserId(video.getUserId());
            }
        }

        this.mongoTemplate.save(comment);
        return true;
    }

    @Override
    public Long queryCommentCount(String publishId, Integer type) {
        //先判断有没有爱过
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(type));
        return this.mongoTemplate.count(query, Comment.class);
    }

    @Override
    public Publish queryPublishById(String id) {
        return this.mongoTemplate.findById(new ObjectId(id), Publish.class);
    }

    @Override
    public List<Comment> queryCommentList(String publishId, Integer page, Integer pageSize) {

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.asc("created")));

        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(2)).with(pageRequest);

        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);

        return commentList;
    }

    @Override
    public List<Comment> queryCommentListByUser(Long userId, Integer type, Integer page, Integer pageSize) {

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = new Query(Criteria
                .where("publishUserId").is(userId)
                .and("commentType").is(type)).with(pageRequest);

        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);
        return commentList;
    }

    @Override
    public List<Publish> queryPublishByPids(List<Long> pids) {
        Query query = Query.query(Criteria.where("pid").in(pids));
        return this.mongoTemplate.find(query, Publish.class);
    }

    @Override
    public List<Publish> queryAlbumList(Long userId, Integer page, Integer pageSize) {
        //查询相册表
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = new Query().with(pageRequest);
        List<Album> albums = this.mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);
        if (CollectionUtils.isEmpty(albums)) {
            return null;
        }

        List<ObjectId> idList = albums.stream().map(Album::getPublishId).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("id").in(idList));
        return this.mongoTemplate.find(query1, Publish.class);
    }
}